package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.PropertyUtil;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsOwnerMapper;
import com.jy.wms.dao.WmsSetBoxMapper;
import com.jy.wms.pojo.SysHz;
import com.jy.wms.pojo.WmsOwner;
import com.jy.wms.pojo.WmsSetBox;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
    * @ClassName: WmsSetBoxService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Jane
    * @Date Fri Jan 26 10:47:42 CST 2018
    */

    @Service
    public class WmsSetBoxService extends BaseService<WmsSetBoxMapper,WmsSetBox> {

        @Autowired
        private WmsOwnerMapper wmsOwnerMapper;

    @BaseServiceDescribe(moduleName = "集拼箱",btnName = "修改箱型")
        public void setXx(String xxid,String id) throws ServiceException,SucessException{
        try {
            dao.updateJpxid(xxid,id);
            throw new SucessException("修改箱型成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new SucessException("修改箱型失败");
        }
    }

    @BaseServiceDescribe(moduleName = "集拼箱",btnName = "查询箱编号")
    public JSONObject getXmx(Map<String,Object> mapCs,HttpSession session){
        JSONObject json = new JSONObject();
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        mapCs.put("ckid",String.valueOf(userinfo.getUser().getOrgId().get(0)));
        List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
        if(hz.size()>0){
            WmsOwner wmsOwner =  wmsOwnerMapper.baseSelectByPrimaryKey(hz.get(0).getHzid());
            if(wmsOwner.getCkfh().equals("1")){
                mapCs.put("fh","1");
            }
        }
        List<Map<String,Object>> list = dao.getXmx(mapCs);
        if(list.size()>0){
            Double sum = 0.0;
            for(int i = 0;i < list.size();i++){
                if(list.get(i).get("zl") != null){
                    sum += Double.valueOf(list.get(i).get("zl").toString());
                }
            }
            json.put("zzl",sum);
            json.put("contentList",list);
            json.put("totals",list.size());
            json.putAll(dao.getBoxNumber(mapCs.get("xbh").toString(),mapCs.get("ckid").toString()));
        }
        json.put("lxr",userinfo.getUser().getShow_rent() == null ? "" : userinfo.getUser().getShow_rent());
        json.put("dz",userinfo.getUser().getAddress() == null ? "" : userinfo.getUser().getAddress());
        return json;
    }

    @BaseServiceDescribe(moduleName = "集拼箱",btnName = "查询箱型")
    public List<Map<String,Object>> getXx(HttpSession session){
        List<Map<String,Object>> map = new ArrayList<Map<String,Object>>();
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
        String hzid = "";
        if(hz.size()>0){
            hzid = hz.get(0).getHzid();
        }
        map = dao.getXx(hzid,String.valueOf(userinfo.getUser().getOrgId().get(0)));
        return map;
    }

     /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert( WmsSetBox entity){
         return dao.baseInsert( entity );
    }

    /**
     * 打印信息
     * @param id
     * @return
     */
    public JSONObject print(String id,HttpSession session) throws Exception{
        JSONObject json = new JSONObject();
        json.put("fydh",dao.getFydh(id));
            WmsSetBox wmsSetBox = dao.baseSelectByPrimaryKey(id);
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                json.put("hzmc",hz.get(0).getShow_hzid());
            }
        json.put("ckmc",userinfo.getUser().getOrgName());
        json.put("cklxr",userinfo.getOrgs().get(0).getMaster());
        json.put("lxr",wmsSetBox.getLxr());
        json.put("dz",wmsSetBox.getDz());
            String host = PropertyUtil.getProperty("safety.host");
            String port = PropertyUtil.getProperty("safety.port");
            String result = HttpUtil.doGet("http://"+host+":"+port+"/ms-safety/org/getOrgInfo/"+String.valueOf(userinfo.getUser().getOrgId().get(0)),session.getId());
        json.put("ckdz",JSONObject.fromObject(result).get("address") == null?"":JSONObject.fromObject(result).get("address"));
        json.put("kfrx",userinfo.getOrgs().get(0).getTelephone() == null?"":userinfo.getOrgs().get(0).getTelephone());
        json.put("list",dao.getPrintList(id));
        return json;
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象
    * @return int
    */
   @BaseServiceDescribe(moduleName = "集拼箱",btnName = "新增集拼箱")
   @Transactional
    public void baseInsertSelective( WmsSetBox entity)throws ServiceException,SucessException {
       entity.setId(UUIDUtils.uuid());
       SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
       String xbh = "JPX" + df.format(new Date())+Integer.toString((int)(Math.random()*9+1)*1000);
       while (dao.getCountByXbh(xbh) > 0 ){
           xbh = "JPX" + df.format(new Date())+Integer.toString((int)(Math.random()*9+1)*1000);
       }
       entity.setXbh(xbh);
       Map<String,Object> map = new HashMap<String,Object>(2);
       List<String> xbhList = dao.getListByBox(entity.getIds());
       if(xbhList.size()>0){
           StringBuffer msg = new StringBuffer();
           msg.append("箱编号：");
           for (String s : xbhList) {
               msg.append( s +",");
           }
           msg.append("已加入集拼箱不可操作");
           throw new ServiceException(msg.toString());
       }
       map.put("ids",entity.getIds());
       map.put("jpxid",entity.getId());
       dao.updateWmsBoxJpxid(map);
       dao.baseInsertSelective( entity);
       throw new SucessException("新增集拼箱成功");
   }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id){
         return dao.baseDeleteByPrimaryKey( id);
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsSetBox>
    */
    public Page<WmsSetBox> baseSelectPage(WmsSetBox entity ){
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<WmsSetBox>)dao.baseSelectPage( entity );
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsSetBox
    */
    public WmsSetBox baseSelectByPrimaryKey( String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys( List<WmsSetBox> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改 （匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKeySelective( WmsSetBox entity){
         return dao.baseUpdateByPrimaryKeySelective( entity);
    }

   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsSetBox entity){
         return dao.baseUpdateByPrimaryKey( entity);
    }
}
